//
//  JXDMapViewController.swift
//  MeetAround
//
//  Created by apple on 2020/11/20.
//  Copyright © 2020 FurtureTech. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation
class JXDMapViewController: UIViewController {
    
    @IBOutlet weak var mapView: MKMapView!
    
    @IBOutlet weak var tf: UITextField!
    
    var locationManager: CLLocationManager!
    
    var annotationView: UIImageView!
    
    var currentLocation: MKUserLocation?
    
    var finalLocation: CLLocation?
    
    var gerCoder: CLGeocoder!
    
    var handler: ((String) -> (Void))
    
    
    init(handler: @escaping ((String) -> (Void))) {
        self.handler = handler
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @IBAction func back(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "选择送货地址"
        configLocation()
    }
    
    func configLocation(){
        gerCoder = CLGeocoder()
//        locationManager = CLLocationManager()
//        locationManager.delegate = self
        mapView.isRotateEnabled = false
        mapView.delegate = self
        
        self.annotationView = UIImageView(image: UIImage(named: "电站图标"))
        self.annotationView.frame = CGRect(x: self.mapView.center.x - 15, y: self.mapView.center.y, width: 30, height: 40);
        mapView.addSubview(annotationView)
        self.mapView.userTrackingMode = .follow;
//        if (CLLocationManager.locationServicesEnabled()) {
//               //设置定位精度
//            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//            self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次(这里的设置为每隔百米)
//            self.locationManager.delegate = self;
//            //使用应用程序期间允许访问位置数据
//            self.locationManager.requestWhenInUseAuthorization()
//            self.locationManager.startUpdatingLocation()
//           }
        
    }

    @IBAction func clickConfirmBtn(_ sender: UIButton) {
        
        if self.tf.text?.count == 0{
            
//            self.noticeOnlyText("请选择地址")
            return
        }
        
        handler(self.tf.text!)
        self.navigationController?.popViewController(animated: true)
        
    }
    
}

extension JXDMapViewController: CLLocationManagerDelegate, MKMapViewDelegate{
    
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        if(self.currentLocation == nil){
            self.currentLocation = userLocation
            self.setRegion(with: userLocation.coordinate)
        }
        
//        self.locationManager.stopUpdatingLocation()
    }
    
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        
        let centerCoordinate = mapView.region.center;
        
        //测试红点标注地图中心
        self.view.bringSubviewToFront(self.annotationView)
        
        
        //当前地图中心点坐标
        let centerLocation = CLLocation(latitude: centerCoordinate.latitude, longitude: centerCoordinate.longitude)
        
        self.finalLocation = centerLocation
        
        encoderCurrentPlace(coderLocation: centerLocation)
        
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
//        let current = locations.last
        
    }
    
    
    func setRegion(with coordinate: CLLocationCoordinate2D){
        
        let region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1));
        let adjustedRegion = self.mapView.regionThatFits(region)
        self.mapView.setRegion(adjustedRegion, animated: true)
        self.annotationView.center = CGPoint(x: self.mapView.center.x, y: self.mapView.center.y)
        
    }
    
    func encoderCurrentPlace(coderLocation: CLLocation){
        
        var address: String = "";
        self.gerCoder.reverseGeocodeLocation(coderLocation) { (placemarks, err) in
            
            let placeMark = placemarks?.first!;
            var city = placeMark?.locality;
            if city?.count == 0{
                city = placeMark?.administrativeArea
            }

        
            if let c = city{
                address = address + c
            }
            
            if let subLocality = placeMark?.subLocality{
                
                address = address + subLocality
            }
            
            if let thoroughfare = placeMark?.thoroughfare{
                address = address + thoroughfare
            }
            
            print("\(address)")
            self.tf.text = address
        }
        
        
    }
    
}
